package com.sl.au.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.EXDELoginInfo;
import com.sl.au.entity.Option;
import com.sl.au.entity.SaleArea;
import com.sl.au.entity.User;
import com.sl.au.repository.EXDELoginInfoRepository;
import com.sl.au.service.OptionService;
import com.sl.au.service.SaleAreaService;
import com.sl.au.service.UserService;

import net.sourceforge.pinyin4j.PinyinHelper;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping(value = "/ui/user")
public class UserController extends BaseController {


	@Autowired
	UserService userService;
	@Autowired
	OptionService optionService;
	@Autowired
	SaleAreaService saleAreaService;
	@Autowired
	EXDELoginInfoRepository exdeLoginRepository;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("user/userindex");
		String group = "上级部门";
		List<Option> superiors = new ArrayList<Option>();
		List<SaleArea> saleAreas = new ArrayList<SaleArea>();
		List<EXDELoginInfo> men=exdeLoginRepository.getNoRole();
		superiors= optionService.getRepository().findByGroup(group);
		saleAreas= saleAreaService.getRepository().getAllSaleArea();
		modelAndView.addObject("saleAreas", saleAreas);
		modelAndView.addObject("superiors", superiors);
		modelAndView.addObject("men", men);
		return modelAndView;
	}

	/**
	 * 新增弹窗用户下拉数据
	 * @return
	 */
	@RequestMapping(value = "/getmen", method = RequestMethod.GET)
	public Map<Object,Object> getStaff(HttpServletRequest request) {
		Map<Object,Object> map = new HashMap<Object,Object>();
		List<EXDELoginInfo> men=exdeLoginRepository.getNoRole();
		map.put("men", men);
		return map;
	}
	@RequestMapping(value = "noaccount", method = RequestMethod.GET)
	public Map<String,Object> newAccount() {
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("data",userService.getRepository().findAccountIsNull());
		map.put("code", 0);
		return map;
	}
	/**
	 * 保存
	 * @return
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Map<String, Object> saveSaleChance(HttpServletRequest request, @RequestBody User user) {
		Map<String, Object> map = new HashMap<String, Object>();
		String areaId = request.getParameter("areaId");
		if(areaId != null){
			User userEdit =userService.getRepository().findOne(areaId);
			if(userEdit != null){
				userEdit.setName(user.getName());
				userEdit.setOrderNum(user.getOrderNum());
				userEdit.setPosition(user.getPosition());
				userEdit.setContactType(user.getContactType());
				userEdit.setEmail(user.getEmail());
				userEdit.setSex(user.getSex());
				userEdit.setSaleArea(user.getSaleArea());
				userService.getRepository().save(userEdit);	
			}
		}
		else{		
			userService.getRepository().save(user);	
		}
		map.put("code", 0);
		return map;
	}
	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		List<User> users =null;
		int count=0;
		if (org.springframework.util.StringUtils.hasText(key)){
			users=userService.getUsers(start, length, key, null, null);		
		}else {
			users=userService.getPage(start, length, null, null, null);			
		}
		count=userService.getCount(key);
		map.put("data", users);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	@RequestMapping(value="{userId}",method = RequestMethod.DELETE)
	public Map<String, Object> deleteUser(@PathVariable String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		int code=-1;
		userService.delete(userId);	
		code=0;
		map.put("code", code);
		return map;
	}
	/**
	 * 根据选择的部门过滤片区信息下拉框选项
	 */
	@RequestMapping(value = "getAreaOption", method = RequestMethod.GET)
	public Map<String, Object> getAreaOption(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String superior = request.getParameter("superior");
		List<SaleArea> saleAreas= saleAreaService.getRepository().findBySuperior(superior);
		map.put("saleAreas", saleAreas);
		return map;
	}
	//移动端获得通讯录
	@RequestMapping(value = "mobileGetPage", method = RequestMethod.GET)
	public Map<String, Object> mobileGetPage(HttpServletRequest request) {
//		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		List<User> users =null;
		int count=0;
		if (org.springframework.util.StringUtils.hasText(key)){
			users=userService.getUsers(start, length, key, null, null);		
		}else {
			users=userService.getPage(start, length, null, null, null);			
		}
		count=userService.getCount(key);
		Map<String, Object> map=getSortData(users);
//		map.put("data", map1);
//		map.put("draw", request.getParameter("draw"));
//		map.put("recordsFiltered", count);
//		map.put("recordsTotal", count);
		return map;
	}
    /**
     * 得到中文首字母 
     * 
     * @param str
     * @return
     */
    public static String getPinYinHeadChar(String str) {
        String convert = null;
            char[] word = str.toCharArray();
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word[0]);
            if (pinyinArray != null) {
            	char[] a=pinyinArray[0].toCharArray();
                convert =String.valueOf(a[0]);
            } else {
                convert ="1";  
            }
        return convert;
    }
    //按首字母分类
	public static Map getSortData(List<User> users) {
    	Map<String, Object> map = new HashMap<String, Object>();
//    	Map<String, Object> map1 = new HashMap<String, Object>();
    	List<User> q=new ArrayList<User>();
    	ArrayList<Integer> w=new ArrayList<Integer>();//数组w为分类情况：其中俩个一组，前一个表示首字母的Ascall码，后一个表示数量
        for(int i=97;i<=123;i++){
        	int c=0;
        	for(int j=0;j<users.size();j++){
        		if(users.get(j).getName().isEmpty()){
        			;
        		}else{
            		char[]a=getPinYinHeadChar(users.get(j).getName()).toCharArray();
            		if(a[0]==i){
            			q.add(users.get(j));
            			c++;
            		}
        		}
        		}
        	//将剩余的对象分成一类
        	if(i==123){
        		for(int x=0;x<users.size();x++){
        			Boolean j=true; 
        			for(int y=0;y<q.size();y++){
        				if(users.get(x).getId().equals(q.get(y).getId())){
        					j=false;
        				}
        			}
        			if(j){
        				q.add(users.get(x));
        				c++;
        			}
        		}
        	}
        	if(c==0){
        		;
        	}else{
        		w.add(i);
        		w.add(c);
        		map.put("record", w);
        		map.put("data", q);
        	}
        }
        return map;
    }
	//移动端保存电话号码
	@RequestMapping(value = "changeTelphoneNumber", method = RequestMethod.GET)
	public Map<String, Object> changeTelphoneNumber(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		String telphoneNumber=request.getParameter("telphoneNumber");
		User user =userService.getRepository().findOne(id);
		int judge=0;
//		if(checkMobileNumber(telphoneNumber)){
			user.setContactType(telphoneNumber);
			userService.getRepository().save(user);
			judge=1;
//		}
		map.put("data", judge);
		return map;
	}
	//移动端保存电子邮箱
	@RequestMapping(value = "changeEmail", method = RequestMethod.GET)
	public Map<String, Object> changeEmail(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		String email=request.getParameter("email");
		User user =userService.getRepository().findOne(id);
		int judge=0;
//		if(checkEmail(email)){
			user.setEmail(email);
			userService.getRepository().save(user);
			judge=1;
//		}
		map.put("data", judge);
		return map;
	}
	//移动端获得电话号码和邮箱
	@RequestMapping(value = "getEt", method = RequestMethod.GET)
	public Map<String, Object> getEt(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		User user =userService.getRepository().findOne(id);
		map.put("email", user.getEmail());
		map.put("telphoneNumber", user.getContactType());
		return map;
	}
    /**
     * 验证邮箱
     * @param email
     * @return
     */
//    public static boolean checkEmail(String email){
//        boolean flag = false;
//        try{
//                String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
//                Pattern regex = Pattern.compile(check);
//                Matcher matcher = regex.matcher(email);
//                flag = matcher.matches();
//            }catch(Exception e){
//                flag = false;
//            }
//        return flag;
//    }
     
    /**
     * 验证手机号码
     * @param mobiles
     * @return
     */
//    public static boolean checkMobileNumber(String mobileNumber){
//        boolean flag = false;
//        try{
//                Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
//                Matcher matcher = regex.matcher(mobileNumber);
//                flag = matcher.matches();
//            }catch(Exception e){
//                flag = false;
//            }
//        return flag;
//    }
}
